package cn.ztuo.bitrade.util;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * @author jiaohehe
 * 对象操作
 */
public class BeanUtil {

  public static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<>();
    for (PropertyDescriptor pd : pds) {
      Object srcValue = src.getPropertyValue(pd.getName());
      if (srcValue == null){
        emptyNames.add(pd.getName());
      }
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
  }



  /**
   * vo do之间的对考，要求属性名相同，类型匹配
   * @param target 目标
   * @param resource 源
   */
  public static void copyProperties(Object target, Object resource) {
    try {
      PropertyUtils.copyProperties(target, resource);
    } catch (Exception e) {
      String msg ="对象参数复制异常！";
      throw new RuntimeException(msg);
    }
  }

  /**
   * 非空拷贝
   * @param source
   * @param target
   */
  public static void copyNotNullBean(Object source, Object target) {
    BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
  }
}
